Add json liquid filter to serialize data to a JSON string

Example: `{{ data | json}}` takes the object of the payloads data key and converts it to JSON

Dominik Sander 9 年之前
父节点
当前提交
785ba7091f
共有 2 个文件被更改,包括 15 次插入0 次删除
  1. 5 0
      app/concerns/liquid_interpolatable.rb
  2. 10 0
      spec/concerns/liquid_interpolatable_spec.rb

+ 5 - 0
app/concerns/liquid_interpolatable.rb

@@ -220,6 +220,11 @@ module LiquidInterpolatable
220 220
       input.to_s.sub(Regexp.new(regex), unescape_replacement(replacement.to_s))
221 221
     end
222 222
 
223
+    # Serializes data as JSON
224
+    def json(input)
225
+      JSON.dump(input)
226
+    end
227
+
223 228
     private
224 229
 
225 230
     def logger

+ 10 - 0
spec/concerns/liquid_interpolatable_spec.rb

@@ -48,6 +48,16 @@ describe LiquidInterpolatable::Filters do
48 48
     end
49 49
   end
50 50
 
51
+  describe "json" do
52
+    let(:agent) { Agents::InterpolatableAgent.new(name: "test") }
53
+
54
+    it 'serializes data to json' do
55
+      agent.interpolation_context['something'] = {foo: 'bar'}
56
+      agent.options['cleaned'] = '{{ something | json }}'
57
+      expect(agent.interpolated['cleaned']).to eq('{"foo":"bar"}')
58
+    end
59
+  end
60
+
51 61
   describe 'to_xpath' do
52 62
     before do
53 63
       def @filter.to_xpath_roundtrip(string)